<template>
  <div class="chart-style-panel">
    <!-- <Button class="full-width-btn" @click="chartDataEditorVisible = true">
      <IconEdit class="btn-icon" /> 编辑图表数据
    </Button> -->

    <!-- <Divider /> -->

    <!-- <template v-if="handleElement.chartType === 'line'">
      <div class="row">
        <Checkbox class="row-title" @change="e => updateOptions({ showArea: e.target.checked })" :checked="showArea"
          style="flex: 1;">面积图样式</Checkbox>
        <Checkbox class="row-title" @change="e => updateOptions({ showLine: !e.target.checked })" :checked="!showLine"
          style="flex: 1;">散点图样式</Checkbox>
      </div>
      <div class="row">
        <Checkbox class="row-title" @change="e => updateOptions({ lineSmooth: e.target.checked })"
          :checked="lineSmooth">使用平滑曲线</Checkbox>
      </div>
    </template> -->
    <!-- <div class="row" v-if="handleElement.chartType === 'bar'">
      <Checkbox class="row-title" @change="e => updateOptions({ horizontalBars: e.target.checked })"
        :checked="horizontalBars">条形图样式</Checkbox>
    </div>
    <div class="row" v-if="handleElement.chartType === 'pie'">
      <Checkbox class="row-title" @change="e => updateOptions({ donut: e.target.checked })" :checked="donut">环形图样式
      </Checkbox>
    </div> -->

    <!-- <Divider /> -->
    <ElementFilter />
    <Divider />
    
    <div class="row flex" @click="toggleBox">
      <div class="row-title">容器</div>
      <div class="jiantou-wrapper jiantou" >
        <i class="appIcon-iconfont appIcon-jiantou" :class="{'on': chartProps.box}"></i>
      </div>
    </div>
    <div class="row row-inside" v-if="chartProps.box">
        <div class="row-title" style="flex: 1">距离</div>
        <div class="jiantou-wrapper" style="flex: 3;">
          <dd>
            <Input placeholder="" @change="(value: any) => handleAttribute(value, 'top')" v-model:value="grid.top" class="inp"/>
            <span>上侧距离</span>
          </dd>
          <dd>
            <a-input placeholder="" @change="(value: any) => handleAttribute(value, 'right')" v-model:value="grid.right" class="inp"/>
            <span>右侧距离</span>
          </dd>
          <dd>
            <a-input placeholder="" @change="(value: any) => handleAttribute(value, 'bottom')" v-model:value="grid.bottom" class="inp"/>
            <span>下侧距离</span>
          </dd>
          <dd>
            <a-input placeholder="" @change="(value: any) => handleAttribute(value, 'left')" v-model:value="grid.left" class="inp"/>
            <span>左侧距离</span>
          </dd>
        </div>
    </div>
    <Divider />

    <div class="row">
      <div class="row-title" style="flex: 2">图例：</div>
      <div class="switch-wrapper" style="flex: 3;">
        <Switch :checked="chartProps.legend" @change="value => updateLegend(value)" />
      </div>
      <!-- <Select
        style="flex: 3"
        :value="legend"
        @change="(value:any) => updateLegend(value)"
      >
        <SelectOption value="">不显示</SelectOption>
        <SelectOption value="top">显示在上方</SelectOption>
        <SelectOption value="bottom">显示在下方</SelectOption>
      </Select> -->
    </div>

    <Divider />

    <div class="row">
      <div class="row-title" style="flex: 2">背景填充：</div>
      <Popover trigger="click">
        <template #content>
          <ColorPicker
            :modelValue="fill"
            @update:modelValue="(value:any) => updateFill(value)"
          />
        </template>
        <ColorButton :color="fill" style="flex: 3" />
      </Popover>
    </div>
    <div class="row">
      <div class="row-title" style="flex: 2">圆角：</div>
      <InputNumber
        v-model:value="borderRadius"
        min="0"
        @change="(value:any) => updateborderRadius(value)"
        style="flex: 3"
      />
    </div>
    <ElementWidthHeight />

    <!-- <div class="row">
      <div class="row-title" style="flex: 2;">网格颜色：</div>
      <Popover trigger="click">
        <template #content>
          <ColorPicker :modelValue="gridColor" @update:modelValue="value => updateGridColor(value)" />
        </template>
        <ColorButton :color="gridColor" style="flex: 3;" />
      </Popover>
    </div> -->

    <!-- <div v-if="handleElement?.data.type.type != '2DMAP1'"> -->
    <Divider />
    <div class="row" v-for="(color, index) in themeColor" :key="index">
      <div class="row-title" style="flex: 2">
        {{ index === 0 ? "主题配色：" : "" }}
      </div>
      <Popover trigger="click">
        <template #content>
          <!-- @update:modelValue="(value:any) => updateTheme(value, index)" -->
          <ColorPicker
            :modelValue="color"
            @update:modelValue="(value:any) => updateTheme(value, index)"
          />
        </template>
        <div class="color-btn-wrap" style="flex: 3">
          <ColorButton :color="color" style="width: 100%" />
          <Tooltip :mouseLeaveDelay="0" :mouseEnterDelay="0.5" title="删除">
            <div
              class="delete-color-btn"
              @click.stop="deleteThemeColor(index)"
              v-if="index !== 0"
            >
              <IconCloseSmall />
            </div>
          </Tooltip>
        </div>
      </Popover>
    </div>
    <ButtonGroup class="row">
      <Popover trigger="click" v-model:visible="presetThemesVisible">
        <template #content>
          <div class="preset-themes">
            <div
              class="preset-theme"
              v-for="(item, index) in presetChartThemes"
              :key="index"
              @click="applyPresetTheme(item)"
            >
              <div
                class="preset-theme-color"
                v-for="color in item"
                :key="color"
                :style="{ backgroundColor: color }"
              ></div>
            </div>
          </div>
        </template>
        <Button class="no-padding" style="flex: 2">推荐主题</Button>
      </Popover>
      <Button
        class="no-padding"
        :disabled="themeColor.length >= 10"
        style="flex: 3"
        @click="addThemeColor()"
      >
        <IconPlus class="btn-icon" /> 添加主题色
      </Button>
    </ButtonGroup>
  </div>
  <Divider />

  <ElementOutline />
  <Modal
    v-model:visible="chartDataEditorVisible"
    :footer="null"
    centered
    :closable="false"
    :width="648"
    destroyOnClose
  >
    <ChartDataEditor
      :data="handleElement.data"
      :element="handleElement"
      @close="chartDataEditorVisible = false"
      @save="(value:any) => updateData(value)"
      @updateTheme="(data:any) => updateTheme(data.color, data.index)"
    />
  </Modal>
  <!-- </div> -->
</template>

<script lang="ts" setup>
import { defineComponent, nextTick, onUnmounted, reactive, ref, watch } from "vue";
import {
  IBarChartOptions,
  ILineChartOptions,
  IPieChartOptions,
} from "chartist";
import { storeToRefs } from "pinia";
import { useMainStore, useSlidesStore } from "@/store";
import { ChartData, PPTChartElement } from "@/types/slides";
import emitter, { EmitterEvents } from "@/utils/emitter";
import useHistorySnapshot from "@/hooks/useHistorySnapshot";

import ElementOutline from "../../common/ElementOutline.vue";
import ElementWidthHeight from "../../common/ElementWidthHeight.vue";
import ColorButton from "../../common/ColorButton.vue";
import ChartDataEditor from "./ChartDataEditor.vue";
import tinycolor from "tinycolor2";
import ElementFilter from '../../common/ElementFilter.vue'

const presetChartThemes = [
  ["#d87c7c", "#919e8b", "#d7ab82", "#6e7074", "#61a0a8", "#efa18d"],
  ["#dd6b66", "#759aa0", "#e69d87", "#8dc1a9", "#ea7e53", "#eedd78"],
  ["#516b91", "#59c4e6", "#edafda", "#93b7e3", "#a5e7f0", "#cbb0e3"],
  ["#893448", "#d95850", "#eb8146", "#ffb248", "#f2d643", "#ebdba4"],
  ["#4ea397", "#22c3aa", "#7bd9a5", "#d0648a", "#f58db2", "#f2b3c9"],
  ["#3fb1e3", "#6be6c1", "#626c91", "#a0a7e6", "#c4ebad", "#96dee8"],
  ["#fc97af", "#87f7cf", "#f7f494", "#72ccff", "#f7c5a0", "#d4a4eb"],
  ["#c1232b", "#27727b", "#fcce10", "#e87c25", "#b5c334", "#fe8463"],
  ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
  ["#e01f54", "#001852", "#f5e8c8", "#b8d2c7", "#c6b38e", "#a4d8c2"],
  ["#c12e34", "#e6b600", "#0098d9", "#2b821d", "#005eaa", "#339ca8"],
  ["#8a7ca8", "#e098c7", "#8fd3e8", "#71669e", "#cc70af", "#7cb4cc"],
];
const hasFilters = ref(false)

const mainStore = useMainStore();
const slidesStore = useSlidesStore();
const { handleElement, handleElementId }: any = storeToRefs(mainStore);
const { theme, currentSlide } = storeToRefs(slidesStore);

const chartDataEditorVisible = ref(false);
const presetThemesVisible = ref(false);

const { addHistorySnapshot } = useHistorySnapshot();

const fill = ref<string>();
const borderRadius = ref();

const themeColor = ref<string[]>([]);
const gridColor = ref("");
const legend = ref("");
const chartProps = reactive({
  box: false,
  xVisible: false,
  yVisible: false,
  x: false,
  y: false,
  legend: false
})
let grid = ref({
  top:50,
  right:10,
  bottom:20,
  left:40,
})
const lineSmooth = ref(true);
const showLine = ref(true);
const showArea = ref(false);
const horizontalBars = ref(false);
const donut = ref(false);
const handleAttribute = (val: any, direcion: any) => {
   console.log(val,val.target.value,'---');
   if(direcion == 'left') {
    grid.value.left = parseInt(val.target.value)
   }
   if(direcion == 'right') {
    grid.value.right = parseInt(val.target.value)
   }
   if(direcion == 'top') {
    grid.value.top = parseInt(val.target.value)
   }
   if(direcion == 'bottom') {
    grid.value.bottom = parseInt(val.target.value)
   }
    updateElement({ attribute: {
        grid: {
          left: grid.value.left,
          right: grid.value.right,
          top: grid.value.top,
          bottom: grid.value.bottom,
        },
        xAxis: {},
        yAxis: {}
      }
    });
}

watch(
  handleElement,
  (val) => {
    if (!handleElement.value || handleElement.value.type !== "chart")
      return;
    fill.value = handleElement.value.fill || "#000";
    borderRadius.value = handleElement.value.borderRadius || 0;
    chartProps.legend = handleElement.value.legend == 'top' ? true : false
    if(handleElement.value.attribute) {
      grid.value = JSON.parse(JSON.stringify(handleElement.value.attribute.grid))
    }
    if (handleElement.value.options) {
      const {
        lineSmooth: _lineSmooth,
        showLine: _showLine,
        showArea: _showArea,
        horizontalBars: _horizontalBars,
        donut: _donut,
      } = handleElement.value.options;

      if (_lineSmooth !== undefined)
        lineSmooth.value = _lineSmooth as boolean;
      if (_showLine !== undefined) showLine.value = _showLine;
      if (_showArea !== undefined) showArea.value = _showArea;
      if (_horizontalBars !== undefined)
        horizontalBars.value = _horizontalBars;
      if (_donut !== undefined) donut.value = _donut;
    }

    themeColor.value = handleElement.value.themeColor;
    gridColor.value = handleElement.value.gridColor || "#333";
    legend.value = handleElement.value.legend || "";
  },
  { deep: true, immediate: true }
);

const updateElement = (props: Partial<PPTChartElement>) => {
  slidesStore.updateElement({ id: handleElementId.value, props });
  addHistorySnapshot();
};

// 设置图表数据
const updateData = (data: any) => {
  chartDataEditorVisible.value = false;
  updateElement({ data });
};

// 设置填充色
const updateFill = (value: string) => {
  updateElement({ fill: value });
};

// 设置圆角
const updateborderRadius = (value: number) => {
  updateElement({ borderRadius: value });
};

// 设置其他选项：柱状图转条形图、折线图转面积图、折线图转散点图、饼图转环形图、折线图开关平滑曲线
const updateOptions = (
  optionProps: ILineChartOptions & IBarChartOptions & IPieChartOptions
) => {
  const _handleElement = handleElement.value as PPTChartElement;

  const newOptions = { ..._handleElement.options, ...optionProps };
  updateElement({ options: newOptions });
};

// 设置主题色
const updateTheme = (color: string, index: number) => {
  // 当主题色是一个并且要设置第二系列及以上的时候，给图表添加一组色值再更改
  if (themeColor.value.length === 1 && index > 0) {
    const colors = tinycolor(themeColor.value[0])
      .analogous(10)
      .map((color) => color.toHexString())
      .map((c, i) => (i === index ? color : c));
    updateElement({ themeColor: colors });
    return;
  } else {
    const props = {
      themeColor: themeColor.value.map((c, i) => (i === index ? color : c)),
    };
    updateElement(props);
  }
};

// 添加主题色
const addThemeColor = () => {
  const props = {
    themeColor: [...themeColor.value, theme.value.themeColor],
  };
  updateElement(props);
};

// 使用预置主题配色
const applyPresetTheme = (colors: string[]) => {
  console.log("11");
  updateElement({ themeColor: colors });
  presetThemesVisible.value = false;
};

// 删除主题色
const deleteThemeColor = (index: number) => {
  const props = {
    themeColor: themeColor.value.filter((c, i) => i !== index),
  };
  updateElement(props);
};

// 设置网格颜色
const updateGridColor = (gridColor: string) => {
  updateElement({ gridColor });
};
const toggleBox = () => {
  chartProps.box = !chartProps.box
}
// 设置图例位置/不显示
const updateLegend = (val: any) => {
  chartProps.legend = !chartProps.legend
  updateElement({ legend: chartProps.legend?'top':'' });
};

const openDataEditor = () => (chartDataEditorVisible.value = true);

emitter.on(EmitterEvents.OPEN_CHART_DATA_EDITOR, openDataEditor);
onUnmounted(() => {
  emitter.off(EmitterEvents.OPEN_CHART_DATA_EDITOR, openDataEditor);
});
</script>

<style lang="scss" scoped>
.row-inside {
  align-items: start !important;
  .row-title {
    font-size: 12px;
    padding-left: 5px;
    line-height: 30px;
  }
}
.row-title {
  cursor: pointer;
  i {
      font-size: 12px;
      display: inline-block;
    }
}
.flex {
  display: flex;
  justify-content: space-between;
}
.jiantou {
  i {
    &::before {
      transition: .5s all ease;
      display: block;
      transform: rotate(-90deg) scale(.6);
      transform-origin: center;
    }
  }
  .on {
    &::before {
      transform: rotate(0deg) scale(.6);
    }
  }
}
.jiantou-wrapper {
  text-align: right;
  dd {
    width: calc(50% - 10px);
    margin-right: 10px;
    float: left;
    text-align: left;
    .inp {
      background: #2F3043;
      border: 0;
      border-radius: 4px;
      color: #fff;
    }
    span {
      display: block;
      padding: 5px 0 10px 0;
    }
  }
}
.switch-wrapper {
  text-align: right;
}
.row {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 22px;
}

.full-width-btn {
  width: 100%;
}

.btn-icon {
  margin-right: 3px;
}

.color-btn-wrap {
  position: relative;
}

.delete-color-btn {
  position: absolute;
  width: 30px;
  right: 2px;
  top: 2px;
  bottom: 2px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  cursor: pointer;
}

.preset-themes {
  width: 250px;
  display: flex;
  margin-bottom: -10px;

  @include flex-grid-layout();
}

.preset-theme {
  display: flex;
  cursor: pointer;

  @include flex-grid-layout-children(2, 48%);
}

.preset-theme-color {
  width: 20px;
  height: 20px;
}

.ant-checkbox-wrapper {
  color: $contentTextColor;
}
</style>
